package wsi.task.typedetector;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class SetDetector extends AbstractDetector {

	private final Set<String> setValue = new HashSet<>();

	public SetDetector() {
		super("set");

	}

	private double _splitTest(List<Collection<String>> l1,
			List<Collection<String>> l2) {
		Set<String> set = new HashSet<>();

		for (Collection<String> i : l1)
			set.addAll(i);

		int a = 0;

		for (Collection<String> i : l2) {
			boolean contained = true;

			for (String j : i)
				if (!set.contains(j)) {
					contained = false;
					break;
				}

			if (contained)
				a++;
		}

		double res = 1. * a / l2.size();
		log.info("_splitTest res: " + res);

		return res;
	}

	@Override
	public double detect(List<String> values) {
		return 0;
	}

	public double detect(List<String> values, List<Collection<String>> valueList) {
		setValue.clear();

		Set<String> _set = new HashSet<>();

		for (String i : values) {
			setValue.add(i);

			if (_set.contains(i))
				continue;

			_set.add(i);
		}

		double ratio = 1. * _set.size() / values.size();

		if (ratio > .4)
			return 0;

		log.info(String.format("ratio: %.2f, diff %d, total %d, set %s", ratio,
				_set.size(), values.size(), _set));

		if (!splitTest(valueList))
			return 0;

		return 1.;
	}

	protected Set<String> getSetValue() {
		return setValue;
	}

	private boolean splitTest(List<Collection<String>> valueList) {
		Collections.shuffle(valueList);

		List<Collection<String>> l1, l2;

		l1 = new ArrayList<>();
		l2 = new ArrayList<>();

		int a = valueList.size() / 2;

		for (int i = 0; i < a; i++)
			l1.add(valueList.get(i));

		for (int i = a; i < valueList.size(); i++)
			l2.add(valueList.get(i));

		double threshold = .9;

		return (_splitTest(l1, l2) > threshold || _splitTest(l2, l1) > threshold);
	}
}
